package com.zh.yida.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zh.yida.common.R;
import com.zh.yida.entity.Employee;
import com.zh.yida.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


@RestController
@RequestMapping("/employee")
@Slf4j
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
//    @Autowired
//    private BCryptPasswordEncoder encoder;

    /**
     * 页面登陆
     * @param req
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest req, @RequestBody Employee employee) {
//        1、将页面提交的密码password进行MD5盐值加密处理
        String s = employee.getPassword();
        String password = DigestUtils.md5DigestAsHex(s.getBytes());
//        System.out.println(password);
//        String password = encoder.encode(s);
//        System.out.println(password);
//        2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(lqw);
//        3、如果没有查询到则返回登录失败结果
        if (emp == null) {
            return R.error("该用户不存在！");
        }
//        4、密码比对，如果不一致则返回登录失败结果
//        if (! encoder.matches(s, emp.getPassword())) {
        if (!password.equals(emp.getPassword())) {
            return R.error("密码不正确！请重新输入！");
        }
//        5、查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if (emp.getStatus() == 0) {
            return R.error("该账号已禁用！");
        }

//        6、登录成功，将员工id存入Session并返回登录成功结果
        HttpSession session = req.getSession();
        session.setAttribute("employee", emp.getId());
        return R.success(emp);
    }

    /**
     * 员工退出
     *
     * @param req
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest req) {
//        1、清理Session中的用户id
        req.getSession().removeAttribute("employee");
//        2、返回结果
        return R.success("退出成功");
    }

    /**
     * 添加用户
     *
     * @param request
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody Employee employee) {
        //设置初始密码，用md5加密
        String password = DigestUtils.md5DigestAsHex("123456".getBytes());
//        Long id = (Long) request.getSession().getAttribute("employee");
        employee.setPassword(password);
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setCreateUser(id);
//        employee.setUpdateUser(id);
        log.info("请求的数据为{}", employee);
        employeeService.save(employee);
        return R.success("保存成功！！");
    }

    /**
     * 页面分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<Employee>> selectPage(int page, int pageSize, String name) {
        log.info("第{}页，共{}条数据，名称为{}", page, pageSize, name);
        //分页构造器
        Page<Employee> employeePage = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        //StringUtils.isNotEmpty(name判断是否为空，相当于if判断）
        lqw.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        lqw.orderByDesc(Employee::getUpdateTime);
        employeeService.page(employeePage, lqw);
        return R.success(employeePage);
    }

    /**
     * 修改用户信息
     * @param req
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(HttpServletRequest req, @RequestBody Employee employee) {
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser((Long) req.getSession().getAttribute("employee"));
        employeeService.updateById(employee);
        return R.success("修改成功");
    }

    @GetMapping("/{id}")
    public R<Employee> selectOne(@PathVariable Long id) {
        Employee employee = employeeService.getById(id);
        employee.setPassword(null);
        return R.success(employee);
    }
}
